﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace CodePlex.ErrorManagement
{
    public static partial class Settings
    {
        /// <summary>
        /// Create an exception for an error code.
        /// </summary>
        /// <param name="enumeration">The enumeration field specifying the error to create.</param>
        /// <param name="information">Formatting information specific to the error string.</param>
        /// <returns></returns>
        public static Exception Exception(this System.Enum enumeration, params object[] information)
        {
            Type enumerationType = enumeration.GetType();
            ConstructorInfo constructor;
            
            object[] attrs = enumerationType.GetField(enumeration.ToString()).GetCustomAttributes(typeof(ErrorExceptionAttribute), true);
            if (attrs == null || attrs.Length == 0)
            {
                constructor = ResourceManagerCache.ResourceInfoForType(enumerationType).DefaultExceptionConstructor;
            }
            else
            {
                ErrorExceptionAttribute attribute = (ErrorExceptionAttribute)(attrs[0]);
                constructor = attribute.ExceptionType.GetConstructor(new Type[] { typeof(string) });
                if (constructor == null)
                {
                    throw ErrorCode.ExceptionDoesNotContainProperConstructor_String.Exception(attribute.ExceptionType);
                }
            }
            return (Exception)constructor.Invoke(new object[] { enumeration.FormatErrorString(information) });
        }
    }
}
